/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PesquisaManutencaoCotacaoView.java
 *
 * Created on 29/06/2011, 18:43:31
 */

package br.com.comprasPublicas.view.pesquisa;

import br.com.comprasPublicas.entity.Cotacao;
import br.com.comprasPublicas.util.FormatadoresUtil;
import br.com.comprasPublicas.util.HibernateUtil;
import br.com.comprasPublicas.view.cadastro.ManutencaoCotacaoView;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author helsen
 */
public class PesquisaManutencaoCotacaoView extends javax.swing.JDialog {

    /** Creates new form PesquisaManutencaoCotacaoView */
    public PesquisaManutencaoCotacaoView(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        preencher_tblCotacoes();
        lista = listar_cotacao();
        preencher_cotacao();
        tblCotacoes.setSelectionMode(0);

        preencher_datas();

        //Método utilizado para centralizar o JFrame na tela
        Dimension tela = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation((tela.width - this.getSize().width) / 2, (tela.height - this.getSize().height) / 2);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtSecao = new javax.swing.JTextField();
        btnSelecionar = new javax.swing.JButton();
        txtCotacao = new javax.swing.JTextField();
        ftxtDataFinal = new javax.swing.JFormattedTextField();
        txtDepartamento = new javax.swing.JTextField();
        ftxtDataInicial = new javax.swing.JFormattedTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblCotacoes = new javax.swing.JTable();
        jLabel7 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        btnPesquisar = new javax.swing.JButton();
        txtPedido = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        txtSecao.setName("txtSecao"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(br.com.comprasPublicas.compraspublicas.ComprasPublicasApp.class).getContext().getResourceMap(PesquisaManutencaoCotacaoView.class);
        btnSelecionar.setFont(resourceMap.getFont("btnSelecionar.font")); // NOI18N
        btnSelecionar.setMnemonic('s');
        btnSelecionar.setText(resourceMap.getString("btnSelecionar.text")); // NOI18N
        btnSelecionar.setName("btnSelecionar"); // NOI18N
        btnSelecionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelecionarActionPerformed(evt);
            }
        });

        txtCotacao.setName("txtCotacao"); // NOI18N

        ftxtDataFinal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM))));
        ftxtDataFinal.setName("ftxtDataFinal"); // NOI18N

        txtDepartamento.setName("txtDepartamento"); // NOI18N

        ftxtDataInicial.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM))));
        ftxtDataInicial.setName("ftxtDataInicial"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tblCotacoes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cotacao", "Pedido", "Data", "Objeto", "Seção", "Departamento"
            }
        ));
        tblCotacoes.setName("tblCotacoes"); // NOI18N
        tblCotacoes.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jScrollPane1.setViewportView(tblCotacoes);

        jLabel7.setFont(resourceMap.getFont("jLabel7.font")); // NOI18N
        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        jLabel9.setFont(resourceMap.getFont("jLabel9.font")); // NOI18N
        jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
        jLabel9.setName("jLabel9"); // NOI18N

        jLabel8.setFont(resourceMap.getFont("jLabel8.font")); // NOI18N
        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N

        jLabel11.setFont(resourceMap.getFont("jLabel11.font")); // NOI18N
        jLabel11.setText(resourceMap.getString("jLabel11.text")); // NOI18N
        jLabel11.setName("jLabel11"); // NOI18N

        jLabel10.setFont(resourceMap.getFont("jLabel10.font")); // NOI18N
        jLabel10.setText(resourceMap.getString("jLabel10.text")); // NOI18N
        jLabel10.setName("jLabel10"); // NOI18N

        jLabel12.setFont(resourceMap.getFont("jLabel12.font")); // NOI18N
        jLabel12.setText(resourceMap.getString("jLabel12.text")); // NOI18N
        jLabel12.setName("jLabel12"); // NOI18N

        btnPesquisar.setFont(resourceMap.getFont("btnPesquisar.font")); // NOI18N
        btnPesquisar.setMnemonic('p');
        btnPesquisar.setText(resourceMap.getString("btnPesquisar.text")); // NOI18N
        btnPesquisar.setName("btnPesquisar"); // NOI18N
        btnPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPesquisarActionPerformed(evt);
            }
        });

        txtPedido.setName("txtPedido"); // NOI18N

        jLabel13.setFont(resourceMap.getFont("jLabel13.font")); // NOI18N
        jLabel13.setText(resourceMap.getString("jLabel13.text")); // NOI18N
        jLabel13.setName("jLabel13"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtCotacao, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel13)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtPedido, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ftxtDataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel9)
                .addGap(18, 18, 18)
                .addComponent(ftxtDataFinal, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(24, 24, 24)
                .addComponent(jLabel10)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtSecao, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(20, 20, 20)
                .addComponent(jLabel11)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSelecionar)
                    .addComponent(btnPesquisar))
                .addContainerGap(15, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(20, 20, 20)
                            .addComponent(jLabel12))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 945, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(17, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel10)
                            .addComponent(jLabel11)
                            .addComponent(jLabel8)
                            .addComponent(txtSecao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(ftxtDataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel9)
                            .addComponent(ftxtDataFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel13)
                            .addComponent(txtPedido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtCotacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7))
                        .addComponent(txtDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnPesquisar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 332, Short.MAX_VALUE)
                .addComponent(btnSelecionar)
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel12)
                    .addGap(38, 38, 38)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 312, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(48, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSelecionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionarActionPerformed
        if (tblCotacoes.getSelectedRow()==-1){
            JOptionPane.showMessageDialog(null, "Nenhuma Cotação Selecionada");
        } else{
            String selecao = tblCotacoes.getModel().getValueAt(tblCotacoes.getSelectedRow(), 0).toString();
            ManutencaoCotacaoView.cot = selecao;
            limpa_objetos();
            dispose();
        }
}//GEN-LAST:event_btnSelecionarActionPerformed

    private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarActionPerformed
        if (ftxtDataInicial.getText().equals("")) preencher_datas();
        lista = listar_parametros();
        preencher_cotacao();
}//GEN-LAST:event_btnPesquisarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PesquisaManutencaoCotacaoView dialog = new PesquisaManutencaoCotacaoView(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnPesquisar;
    private javax.swing.JButton btnSelecionar;
    private javax.swing.JFormattedTextField ftxtDataFinal;
    private javax.swing.JFormattedTextField ftxtDataInicial;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblCotacoes;
    private javax.swing.JTextField txtCotacao;
    private javax.swing.JTextField txtDepartamento;
    private javax.swing.JTextField txtPedido;
    private javax.swing.JTextField txtSecao;
    // End of variables declaration//GEN-END:variables

    private List lista;
    private Cotacao cotacao;

    public void preencher_tblCotacoes()
    {
        try
        {
            tblCotacoes.getColumnModel().getColumn(0).setPreferredWidth(20);
            tblCotacoes.getColumnModel().getColumn(1).setPreferredWidth(20);
            tblCotacoes.getColumnModel().getColumn(2).setPreferredWidth(20);
            tblCotacoes.getColumnModel().getColumn(3).setPreferredWidth(500);
            tblCotacoes.getColumnModel().getColumn(4).setPreferredWidth(50);
            tblCotacoes.getColumnModel().getColumn(5).setPreferredWidth(50);

            DefaultTableModel modelo_tbl = (DefaultTableModel) tblCotacoes.getModel();
            modelo_tbl.setNumRows(0);

        }
        catch(Exception erro)
        {
            JOptionPane.showMessageDialog(null, "Não foi possível preencher tabela "+erro);
        }
    }

    private void preencher_datas() {
        //DataInicial pré-preenchida primeiro dia do ano
        ftxtDataInicial.setText("01/01/2011");

        //DataFinal pré-preenchida data de hoje
        Date hoje = new Date(System.currentTimeMillis());
        String formato = "dd/MM/yyyy";
        SimpleDateFormat formatter = new SimpleDateFormat(formato);
        String dataHoje = formatter.format(hoje);
        ftxtDataFinal.setText(dataHoje);
    }

    private void preencher_cotacao() {
        int tam_lista = lista.size();

        DefaultTableModel modelo_tbl = (DefaultTableModel) tblCotacoes.getModel();
        modelo_tbl.setNumRows(0);

        cotacao = new Cotacao();
        for (int i=0; i<tam_lista; i++ ){
            cotacao = (Cotacao) lista.get(i);
            //alterando o formato da data da cotacao para ex.31/12/2011
            Date dataCotacao = cotacao.getData_emissao();
            String formato = "dd/MM/yyyy";
            SimpleDateFormat formatter = new SimpleDateFormat(formato);
            String dataTabela = formatter.format(dataCotacao);
            modelo_tbl.addRow(new Object[]{cotacao.getId_cotacao(),
                                           cotacao.getPedido().getId_pedido(),
                                           dataTabela,
                                           cotacao.getPedido().getObjeto_compra(),
                                           cotacao.getPedido().getSecao().getSecao(),
                                           cotacao.getPedido().getSecao().getDepartamento().getDepartamento()
                                          } );
        }
        lista = null;
    }

    private List listar_parametros() {
        Session sessao = HibernateUtil.getSessao();
        Transaction transacao = sessao.beginTransaction();

        Criteria c = sessao.createCriteria(Cotacao.class).createAlias("pedido","p").createAlias("pedido.secao", "s").createAlias("pedido.secao.departamento", "d");
        c.addOrder(Order.asc("id_cotacao"));

        //Restrição pela cotacao
        
        if (!txtCotacao.getText().equals("")) {
            int cotacaoBusca = Integer.parseInt(txtCotacao.getText());
            c.add(Restrictions.eq("id_cotacao", cotacaoBusca));
        }

        //Restrição pelo pedido
        if (!txtPedido.getText().equals("")){
            int pedidoBusca = Integer.parseInt(txtPedido.getText());
            c.add(Restrictions.eq("p.id_pedido", pedidoBusca));
        }

        //Restrição pelas datas
        Date dataInicial = Calendar.getInstance().getTime();
        dataInicial = FormatadoresUtil.data2Banco(ftxtDataInicial.getText());
        Date dataFinal = Calendar.getInstance().getTime();
        dataFinal = FormatadoresUtil.data2Banco(ftxtDataFinal.getText());
        c.add(Restrictions.between("data_emissao", dataInicial, dataFinal));

        //Restrição pela seção
        if (!txtSecao.getText().equals("")){
            int idSecao = Integer.parseInt(txtSecao.getText());
            c.add(Restrictions.eq("s.id_secao", idSecao));
        }

        //Restrição pelo departamento
        if (!txtDepartamento.getText().equals("")) c.add(Restrictions.eq("d.id_departamento", Integer.parseInt(txtDepartamento.getText())));

        List listaBusca = c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

        transacao.commit();
        sessao.close();
        return listaBusca;
    }

    private List listar_cotacao() {
        Session sessao = HibernateUtil.getSessao();
        Transaction transacao = sessao.beginTransaction();

        Criteria c = sessao.createCriteria(Cotacao.class);

        List listaBusca = c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

        transacao.commit();
        sessao.close();

        return listaBusca;
    }

    private void limpa_objetos() {
        cotacao = null;
        lista = null;
    }

}
